package com.baoteng.rbspy.jobs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baoteng.rbspy.mq.MessageHandler;

@Component
public class RedisHolder {

	private static final Logger logger = LoggerFactory.getLogger(RedisHolder.class);
	
	@Value("${redis.sub.receiverTopic}")
	private String receiverTopic;
	
	@Value("${redis.sub.senderTopic}")
	private String senderTopic;
	
	@Autowired
	RedisTemplate<String, String> stringRedisTemplate;
	
	@Autowired
	RedisMessageListenerContainer container;
	
	@Autowired
	MessageListenerAdapter receiverListenerAdapter;
	
	@Autowired
    MessageHandler consumer;
	
	@Scheduled(fixedDelay = 2 * 60 * 1000)
	public void sessionRefresh() {
		try {
			logger.info("redis session refresh . last time {}",stringRedisTemplate.opsForValue().get("rbspy_refresh"));
			stringRedisTemplate.convertAndSend(receiverTopic, "gz rb spy heartbeat request .");
			stringRedisTemplate.opsForValue().set("rbspy_refresh", "online_"+System.currentTimeMillis());
			logger.info("redis message container active :{} running :{} autoStrartUp :{}",container.isActive(),container.isRunning(),container.isAutoStartup());
			logger.info("redis session refresh end.");
			if(System.currentTimeMillis() - consumer.getRedisSubHeartbeatTimeStamp() > 6 * 60 * 1000) {
				container.removeMessageListener(receiverListenerAdapter, new PatternTopic(receiverTopic));
				container.addMessageListener(receiverListenerAdapter, new PatternTopic(receiverTopic));
				container.afterPropertiesSet();
			}
		} catch (Exception e) {
			e.printStackTrace();
			container.removeMessageListener(receiverListenerAdapter, new PatternTopic(receiverTopic));
			container.addMessageListener(receiverListenerAdapter, new PatternTopic(receiverTopic));
			container.afterPropertiesSet();
		}
	}
}
